package research.webservice;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.SOAP11Constants;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.transport.http.HTTPConstants;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

/**
 * 很早之前写的一个获取WebService的例子（现在更多的是调用Restful接口）
 * 
 * 解析xml，可以使用jsoup或者OMElement原生的方法.
 * 
 */
public class GetWeatherWebService {
	private static EndpointReference targetEPR = new EndpointReference(
			"http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");

	public String getResult() throws Exception {
		ServiceClient sender = new ServiceClient();
		sender.setOptions(buildOptions());
		OMElement result = sender.sendReceive(buildParam());
		
		System.out.println("原始内容 ：");
		System.out.println(result);
		
		return result.toString();
	}

	private static OMElement buildParam() {
		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMNamespace omNs = fac.createOMNamespace("http://WebXml.com.cn/", "");
		OMElement data = fac.createOMElement("getWeatherbyCityName", omNs);
		OMElement inner = fac.createOMElement("theCityName", omNs);
		inner.setText("北京");
		data.addChild(inner);
		return data;
	}

	private static Options buildOptions() {
		Options options = new Options();
		options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
		options.setAction("http://WebXml.com.cn/getWeatherbyCityName");
		options.setTo(targetEPR);
		options.setProperty(HTTPConstants.CHUNKED, "false");
		// options.setProperty(propertyKey, property)

		// enabling MTOM in the client side
	    //options.setProperty(Constants.Configuration.ENABLE_MTOM,Constants.VALUE_TRUE);
		options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
		return options;
	}

	
	public static void main(String[] args) throws Exception {
		GetWeatherWebService getWeatherWebService = new GetWeatherWebService();
		String result = getWeatherWebService.getResult();
		
		Document doc = Jsoup.parse(result);
		Elements elements = doc.select("getWeatherbyCityNameResult > string");
		
		System.out.println();
		System.out.println("解析：");
		System.out.println(elements.toString());
	}
}
